package service;

import dataAcsessObject.Exception.NotEntityFoundException;
import dataAcsessObject.JPADAOFactory;
import entity.University;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import service.exception.ObjectNotFoundException;
import valueObject.UniversityVO;

/**
 *
 * @author Juan Hernández Serrato
 */
public class UniversityService extends AbstractService<UniversityVO, University> {

    @Override
    public void create(UniversityVO valueObject, EntityManager em) {
        JPADAOFactory.getInstance().getUniversityDAO().create(valueObject.toEntity(), em);
    }

    @Override
    public void update(UniversityVO valueObject, EntityManager em) throws ObjectNotFoundException {
        try {
            University university = JPADAOFactory.getInstance().getUniversityDAO().findById(valueObject.getUserName(), em);
            university = valueObject.toEntity();
            JPADAOFactory.getInstance().getUniversityDAO().update(university, em);
        } catch (NotEntityFoundException ex) {
            throw new ObjectNotFoundException();
        }
    }

    @Override
    public void delete(Object id, EntityManager em) throws ObjectNotFoundException {
        try {
            University university = JPADAOFactory.getInstance().getUniversityDAO().findById(id, em);
            JPADAOFactory.getInstance().getUniversityDAO().delete(university, em);
        } catch (NotEntityFoundException ex) {
            throw new ObjectNotFoundException();
        }
    }

    @Override
    public UniversityVO findById(Object id, EntityManager em) throws ObjectNotFoundException {
        try {
            return JPADAOFactory.getInstance().getUniversityDAO().findById(id, em).toValueObject();
        } catch (NotEntityFoundException ex) {
            throw new ObjectNotFoundException();
        }
    }

    @Override
    public List<UniversityVO> findAll(EntityManager em) {
        List<UniversityVO> universityVOs = new ArrayList<UniversityVO>();
        List<University> universitys = JPADAOFactory.getInstance().getUniversityDAO().findAll(em);
        for (University university : universitys) {
            universityVOs.add(university.toValueObject());
        }
        return universityVOs;
    }

    @Override
    public List<UniversityVO> findRange(int begin, int end, EntityManager em) {
        List<UniversityVO> universityVOs = new ArrayList<UniversityVO>();
        List<University> universitys = JPADAOFactory.getInstance().getUniversityDAO().findRange(begin, end, em);
        for (University university : universitys) {
            universityVOs.add(university.toValueObject());
        }
        return universityVOs;
    }

}
